package com.pengpeng.sheepfoldmall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.pengpeng.sheepfoldmall.product.dao.CategoryBrandRelationDao;
import com.pengpeng.sheepfoldmall.product.service.CategoryBrandRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pengpeng.common.utils.PageUtils;
import com.pengpeng.common.utils.Query;

import com.pengpeng.sheepfoldmall.product.dao.BrandDao;
import com.pengpeng.sheepfoldmall.product.entity.BrandEntity;
import com.pengpeng.sheepfoldmall.product.service.BrandService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {
    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    private CategoryBrandRelationDao categoryBrandRelationDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String key = (String) params.get("key");
        //若参数中带有key则拼接sql
        LambdaQueryWrapper<BrandEntity> queryWrapper = new LambdaQueryWrapper<>();
        if (!StringUtils.isEmpty(key)){
            queryWrapper.like(BrandEntity::getName,key).or().eq(BrandEntity::getBrandId,key).or().eq(BrandEntity::getFirstLetter,key);
        }

        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    /**
     * 如果修改了品牌信息，也要级联修改 分类品牌关系表 中的数据
     * @param brand
     */
    @Transactional
    @Override
    public void updateBrandDetail(BrandEntity brand) {
        //先修改自己的数据
        this.updateById(brand);
        //若此次也更新了品牌名字
        if (!StringUtils.isEmpty(brand.getName())){
            //则还需要更新 分类品牌关联表 中的数据
            categoryBrandRelationService.updateBrand(brand.getBrandId(),brand.getName());

            //TODO:其他级联更新
        }

    }

    /**
     * 删除(并级联删除相关品牌关系)
     * @param asList
     */
    @Override
    public void removeBrandAndRelation(List<Long> asList) {
        this.removeByIds(asList);

        categoryBrandRelationDao.removeBrandAndRelation(asList);
    }
}